<template>
  <div class="task-add-edit-container">
    <!-- 表单区域 -->
    <div class="form-content">
      <div class="form-section">
        <div class="form-item">
          <div class="form-label">任务标题</div>
          <van-field
            v-model="formData.taskTitle"
            placeholder="请输入任务标题"
            maxlength="100"
            show-word-limit
            required
          />
        </div>

        <div class="form-item">
          <div class="form-label">所属队伍</div>
          <van-field
            v-model="selectedTeamName"
            placeholder="请选择队伍"
            readonly
            clickable
            @click="showTeamSelector = true"
            required
          />
          <van-popup
            v-model:show="showTeamSelector"
            position="bottom"
            round
            overlay-style="height: 80%"
          >
            <van-picker
              show-toolbar
              title="选择队伍"
              :columns="teamOptions"
              :default-index="currentTeamIndex"
              @confirm="handleTeamConfirm"
              @cancel="showTeamSelector = false"
            />
          </van-popup>
        </div>

        <div class="form-item">
          <div class="form-label">优先级</div>
          <div class="priority-selector">
            <div
              v-for="item in priorityOptions"
              :key="item.value"
              :class="['priority-item', formData.priority === item.value ? 'active' : '']"
              @click="formData.priority = item.value"
            >
              {{ item.label }}
            </div>
          </div>
        </div>

        <div class="form-item">
          <div class="form-label">负责人</div>
          <van-field
            v-model="assigneeNames"
            placeholder="点击选择负责人"
            readonly
            clickable
            @click="showAssigneeSelector = true"
          >
            <template #right-icon>
              <van-icon name="arrow" class="arrow-icon" />
            </template>
          </van-field>
          <van-popup
            v-model:show="showAssigneeSelector"
            position="right"
            round
            :style="{ width: '80%' }"
          >
            <div class="assignee-selector">
              <div class="assignee-header">
                <div class="assignee-title">选择负责人</div>
                <div class="assignee-close" @click="showAssigneeSelector = false">
                  <van-icon name="close" />
                </div>
              </div>
              <div class="assignee-list">
                <div
                  v-for="member in teamMembers"
                  :key="member.id"
                  :class="['assignee-item', isAssigned(member.id) ? 'active' : '']"
                  @click="toggleAssignee(member.id)"
                >
                  <div class="assignee-info">
                    <div class="assignee-avatar">
                      {{ getAvatarText(member.username) }}
                    </div>
                    <div class="assignee-name">{{ member.username }}</div>
                  </div>
                  <div v-if="isAssigned(member.id)" class="assignee-check">
                    <van-icon name="success" color="#1989fa" />
                  </div>
                </div>
              </div>
              <div class="assignee-footer">
                <div class="cancel-btn" @click="showAssigneeSelector = false">取消</div>
                <div class="confirm-btn" @click="confirmAssignees">确定</div>
              </div>
            </div>
          </van-popup>
        </div>

        <div class="form-item">
          <div class="form-label">截止时间</div>
          <van-field
            v-model="formData.deadline"
            placeholder="选择截止时间"
            readonly
            clickable
            @click="showDatePicker = true"
          >
            <template #right-icon>
              <van-icon name="calendar" />
            </template>
          </van-field>
          <van-popup
            v-model:show="showDatePicker"
            position="bottom"
            round
          >
            <van-date-picker
                :model="formData.deadline"
                title="选择截止时间"
                type="date"
                :min-date="new Date()"
                @confirm="showDatePicker = false"
                @cancel="showDatePicker = false"
            />
          </van-popup>

        </div>

        <div class="form-item">
          <div class="form-label">任务描述</div>
          <van-field
            v-model="formData.description"
            placeholder="请输入任务描述"
            type="textarea"
            rows="4"
            maxlength="500"
            show-word-limit
          />
        </div>

        <div class="form-item" v-if="isEditMode">
          <div class="form-label">任务进度</div>
          <div class="progress-container">
            <van-slider
              v-model="formData.progress"
              :min="0"
              :max="100"
              :step="10"
              show-value
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-action">
      <div class="cancel-btn" @click="handleCancel">取消</div>
      <div class="submit-btn" @click="handleSubmit">保存</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast } from 'vant';
import { taskStore } from '../stores/task/task';
import { userStore } from '../stores/user/user';
import { teamStore } from '../stores/team/team';
import type { Task } from '../models/task';
import type { User } from '../models/user';

const router = useRouter();
const route = useRoute();
const taskStoreAPI = taskStore();
const userStoreAPI = userStore();
const teamStoreAPI = teamStore();

// 获取路由参数
const taskId = computed(() => route.params.id as string);
const teamIdParam = computed(() => route.query.teamId as string);
const isEditMode = computed(() => !!taskId.value);

// 表单数据
const formData = ref({
  taskTitle: '',
  teamId: 0,
  priority: 2, // 默认中优先级
  assigneeIds: [] as number[],
  deadline: '',
  description: '',
  progress: 0,
});

// 状态管理
const loading = ref(false);
const teams = ref<any[]>([]);
const teamMembers = ref<User[]>([]);
const showTeamSelector = ref(false);
const showAssigneeSelector = ref(false);
const showDatePicker = ref(false);
const tempAssigneeIds = ref<number[]>([]);

// 计算属性
const teamOptions = computed(() => {
  return teams.value.map(team => ({
    text: team.name,
    value: team.id,
  }));
});

const currentTeamIndex = computed(() => {
  return teams.value.findIndex(team => team.id === formData.value.teamId);
});

const selectedTeamName = computed(() => {
  const team = teams.value.find(t => t.id === formData.value.teamId);
  return team ? team.name : '';
});

const assigneeNames = computed(() => {
  if (!formData.value.assigneeIds || formData.value.assigneeIds.length === 0) {
    return '未分配';
  }
  const names = formData.value.assigneeIds
    .map(id => {
      const member = teamMembers.value.find(m => m.id === id);
      return member ? member.username : '';
    })
    .filter(Boolean);
  return names.length > 0 ? names.join('、') : '未分配';
});

// 优先级选项
const priorityOptions = [
  { value: 1, label: '低' },
  { value: 2, label: '中' },
  { value: 3, label: '高' },
];

// 获取头像文字
const getAvatarText = (username: string) => {
  return username ? username.charAt(0).toUpperCase() : '?';
};

// 判断用户是否已分配
const isAssigned = (userId: number) => {
  return tempAssigneeIds.value.includes(userId);
};

// 切换负责人选择状态
const toggleAssignee = (userId: number) => {
  const index = tempAssigneeIds.value.indexOf(userId);
  if (index > -1) {
    tempAssigneeIds.value.splice(index, 1);
  } else {
    tempAssigneeIds.value.push(userId);
  }
};

// 确认负责人选择
const confirmAssignees = () => {
  formData.value.assigneeIds = [...tempAssigneeIds.value];
  showAssigneeSelector.value = false;
};

// 处理队伍选择
const handleTeamConfirm = (value: string) => {
  formData.value.teamId = Number(value);
  showTeamSelector.value = false;
  // 加载该队伍的成员
  loadTeamMembers(formData.value.teamId);
};

// 加载队伍成员
const loadTeamMembers = async (teamId: number) => {
  try {
    const res = await teamStoreAPI.getTeamMembers(teamId);
    if (res.code === 200) {
      teamMembers.value = res.data || [];
      // 重置负责人选择
      formData.value.assigneeIds = [];
      tempAssigneeIds.value = [];
    }
  } catch (error) {
    showToast('获取队伍成员失败');
  }
};

// 加载任务详情（编辑模式）
const loadTaskDetail = async () => {
  if (!taskId.value) return;
  try {
    const res = await taskStoreAPI.getTaskDetail(Number(taskId.value));
    if (res.code === 200 && res.data) {
      const task = res.data;
      formData.value = {
        taskTitle: task.task_title || '',
        teamId: task.teamId || 0,
        priority: task.priority || 2,
        assigneeIds: task.assigneeList?.map((a: any) => a.id) || [],
        deadline: task.deadline || '',
        description: task.description || '',
        progress: task.progress || 0,
      };
      // 加载对应队伍的成员
      if (formData.value.teamId) {
        await loadTeamMembers(formData.value.teamId);
      }
    }
  } catch (error) {
    showToast('获取任务详情失败');
  }
};

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  if (!formData.value.taskTitle.trim()) {
    showToast('请输入任务标题');
    return;
  }
  if (!formData.value.teamId) {
    showToast('请选择所属队伍');
    return;
  }

  loading.value = true;
  try {
    const params = {
      taskTitle: formData.value.taskTitle.trim(),
      teamId: formData.value.teamId,
      priority: formData.value.priority,
      assigneeIds: formData.value.assigneeIds,
      deadline: formData.value.deadline || undefined,
      description: formData.value.description.trim(),
      progress: formData.value.progress,
    };

    let res;
    if (isEditMode.value) {
      // 编辑任务
      res = await taskStoreAPI.updateTask(Number(taskId.value), params);
    } else {
      // 创建任务
      res = await taskStoreAPI.createTask(params);
    }

    if (res.code === 200) {
      showToast(isEditMode.value ? '任务更新成功' : '任务创建成功');
      await nextTick();
      router.back();
    } else {
      showToast(res.message || (isEditMode.value ? '任务更新失败' : '任务创建失败'));
    }
  } catch (error) {
    showToast('操作失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  router.back();
};

// 初始化数据
onMounted(async () => {
  // 获取用户信息
  const currentUser = await userStoreAPI.getCurrentUser();
  if (!currentUser) {
    showToast('请先登录');
    router.push('/login');
    return;
  }

  // 获取用户加入的队伍
  try {
    const teamsRes = await teamStoreAPI.getJoinTeams();
    if (teamsRes.code === 200) {
      teams.value = teamsRes.data || [];
      
      // 编辑模式：先加载任务详情，再处理队伍选择
      if (isEditMode.value) {
        await loadTaskDetail();
      } 
      // 创建模式：根据参数或默认选择队伍
      else if (teamIdParam.value) {
        // 从URL参数获取队伍ID
        formData.value.teamId = Number(teamIdParam.value);
        await loadTeamMembers(formData.value.teamId);
      } else if (teams.value.length > 0) {
        // 默认选择第一个队伍
        formData.value.teamId = teams.value[0].id;
        await loadTeamMembers(formData.value.teamId);
      }
    }
  } catch (error) {
    console.error('获取队伍列表失败:', error);
  }
});
</script>

<style scoped>
.task-add-edit-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.form-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.form-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
}

.form-item {
  margin-bottom: 20px;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.priority-selector {
  display: flex;
  gap: 12px;
}

.priority-item {
  flex: 1;
  text-align: center;
  padding: 8px 0;
  border-radius: 4px;
  border: 1px solid #ddd;
  font-size: 14px;
  color: #666;
}

.priority-item.active {
  color: #1989fa;
  border-color: #1989fa;
}

.priority-item:nth-child(1).active {
  color: #1989fa;
  border-color: #1989fa;
}

.priority-item:nth-child(2).active {
  color: #faad14;
  border-color: #faad14;
}

.priority-item:nth-child(3).active {
  color: #f5222d;
  border-color: #f5222d;
}

.arrow-icon {
  transform: rotate(90deg);
}

.progress-container {
  padding: 10px 0;
}

.bottom-action {
  display: flex;
  padding: 16px;
  background-color: #fff;
  gap: 12px;
  border-top: 1px solid #eee;
}

.cancel-btn,
.submit-btn {
  flex: 1;
  padding: 12px;
  border-radius: 4px;
  text-align: center;
  font-size: 16px;
  font-weight: 500;
}

.cancel-btn {
  color: #666;
  background-color: #f5f5f5;
}

.submit-btn {
  color: #fff;
  background-color: #1989fa;
}

/* 负责人选择器样式 */
.assignee-selector {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.assignee-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.assignee-title {
  font-size: 16px;
  font-weight: 600;
}

.assignee-close {
  padding: 4px;
}

.assignee-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.assignee-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.assignee-item.active {
  color: #1989fa;
}

.assignee-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.assignee-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f0f9ff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: 600;
  color: #1989fa;
}

.assignee-name {
  font-size: 16px;
}

.assignee-footer {
  display: flex;
  padding: 16px;
  gap: 12px;
  border-top: 1px solid #eee;
}

.assignee-footer .cancel-btn,
.assignee-footer .confirm-btn {
  flex: 1;
  padding: 12px;
  border-radius: 4px;
  text-align: center;
  font-size: 16px;
}

.assignee-footer .confirm-btn {
  background-color: #1989fa;
  color: #fff;
}
</style>